/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	Dotnetnuke PA module 
	Copyright (c) 2004, Oliver Hine (oliver.hine@gmail.com)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


************************************************************************************************/
using DotNetNuke;
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Data;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.WebAdmin.UserControls;
using Votations.NSurvey.Emailing;
using Votations.NSurvey.Web;
using Votations.NSurvey.Web.Security;


namespace Votations.NSurvey.WebAdmin
{
	public class SurveyMailing : PageBase
	{
		protected System.Web.UI.WebControls.Label MessageLabel;
		protected System.Web.UI.WebControls.Label CreationDateLabel;
		protected System.Web.UI.WebControls.Label LastEntryDateLabel;
		protected HeaderControl Header;
		protected System.Web.UI.WebControls.Button ResetVotesButton;
		protected System.Web.UI.WebControls.Calendar StatsCalendar;
		protected System.Web.UI.WebControls.CheckBox AnonymousEntriesCheckBox;
		protected System.Web.UI.WebControls.Button SendInvitationButton;
		protected System.Web.UI.WebControls.Label PendingEmailsLabel;
		protected System.Web.UI.WebControls.Label AnsweredEmailsLabel;
		protected System.Web.UI.WebControls.TextBox MailingListTextBox;
		protected System.Web.UI.WebControls.TextBox InvitationMessageTextBox;
		protected System.Web.UI.WebControls.TextBox FromTextBox;
		protected System.Web.UI.WebControls.TextBox SubjectTextBox;
		protected System.Web.UI.WebControls.TextBox FromNameTextbox;
		protected System.Web.UI.WebControls.Literal InvitationMailingTitle;
		protected System.Web.UI.WebControls.Literal FromLabel;
		protected System.Web.UI.WebControls.Literal FromNameLabel;
		protected System.Web.UI.WebControls.Literal SubjectLabel;
		protected System.Web.UI.WebControls.Literal InvitationMessageLabel;
		protected System.Web.UI.WebControls.Literal EmailInvitationLabel;
		protected System.Web.UI.WebControls.Literal AnonymousLabel;
		protected SurveyListControl SurveyList;

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			
			CreateLinks();
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.SendInvitationButton.Click += new System.EventHandler(this.SendInvitationButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
		}
		#endregion

		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				SetupSecurity();
				LocalizePage();

				if (!Page.IsPostBack)
				{				
					SurveyList.SurveyId = SurveyId;
					SurveyList.BindDropDown();
					Header.SurveyId = SurveyId;
					FillFields();
				}
			}
			catch( Exception exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException(this,exc);
			}
		}

		private void SetupSecurity()
		{
			CheckRight(NSurveyRights.AccessMailing, true);
		}

		private void LocalizePage()
		{
			InvitationMailingTitle.Text = GetPageResource("InvitationMailingTitle");
			FromLabel.Text = GetPageResource("FromLabel");
			FromNameLabel.Text = GetPageResource("FromNameLabel");
			SubjectLabel.Text = GetPageResource("SubjectLabel");
			if (!Page.IsPostBack)
			{
				SubjectTextBox.Text = GetPageResource("SubjectTextBox");
				FromNameTextbox.Text = GetPageResource("FromNameTextBox");
			}
			InvitationMessageLabel.Text = GetPageResource("InvitationMessageLabel");
			EmailInvitationLabel.Text = GetPageResource("EmailInvitationLabel");
			AnonymousLabel.Text = GetPageResource("AnonymousLabel");
			SendInvitationButton.Text = GetPageResource("SendInvitationButton");

			if (NSurveyUser.Identity is NSurveyFormIdentity)
			{
				FromNameTextbox.Text = 
					((NSurveyFormIdentity)NSurveyUser.Identity).FirstName + " " +
					((NSurveyFormIdentity)NSurveyUser.Identity).LastName;
				FromTextBox.Text = ((NSurveyFormIdentity)NSurveyUser.Identity).Email;
			}
		}

		/// <summary>
		/// Bind the fields
		/// </summary>
		private void FillFields()
		{
			string surveyLink;
			if (Request.ServerVariables["SERVER_PORT"] != null && Request.ServerVariables["SERVER_PORT"] != "80" )

			{
				if (HttpContext.Current.Request.Url.Host != "/")
				{
					surveyLink = string.Format("http://{0}:{1}"+ CurrentFolder("survey.aspx")+"?surveyid={2}&uid=[--invitationid-]", 
						HttpContext.Current.Request.Url.Host, Request.ServerVariables["SERVER_PORT"], SurveyId);
				}
				else
				{
					surveyLink = string.Format("http://{0}:{1}"+ CurrentFolder("survey.aspx")+"?surveyid={2}&uid=[--invitationid-]", 
						HttpContext.Current.Request.Url.Host, Request.ServerVariables["SERVER_PORT"], SurveyId);
				}
			}
			else
			{
				if (HttpContext.Current.Request.Url.Host != "/")
				{
					surveyLink = string.Format("http://{0}"+ CurrentFolder("survey.aspx")+"?surveyid={1}&uid=[--invitationid-]", 
						HttpContext.Current.Request.Url.Host, SurveyId);
				}
				else
				{
					surveyLink = string.Format("http://{0}"+ CurrentFolder("survey.aspx")+"?surveyid={1}&uid=[--invitationid-]", 
						HttpContext.Current.Request.Url.Host, SurveyId);
				}
			}


			InvitationMessageTextBox.Text = 
				string.Format(GetPageResource("InvitationMessageTextBox"), SurveyList.SurveyTitle, surveyLink);
		}

		private void SendInvitationButton_Click(object sender, System.EventArgs e)
		{
			//Init Async call
			ASyncMailing mail = new ASyncMailing();
			ASyncMailingState mailingState = new ASyncMailingState(mail, Session.SessionID);
			AsyncCallback cb = new AsyncCallback(MailingCallback);

			// Build message to send
			EmailingMessage message;
			message = new EmailingMessage();
			message.FromEmail =	FromTextBox.Text;
			message.FromName = FromNameTextbox.Text;
			message.Subject = SubjectTextBox.Text;
			message.Body = InvitationMessageTextBox.Text;
			message.Format = EmailFormat.Text;

			// Dummy session variable to init the session in case
			// it was not initialized
			Session["IamADummy"] = "StartIt";

			// Start the mailing
			mail.BeginMailIt(Session.SessionID, SurveyId, 
				AnonymousEntriesCheckBox.Checked, MailingListTextBox.Text, 
				message, cb, mailingState);

			// Open the poll page while the mailing continues
			UINavigator.NavigateToMailingPoll(SurveyId, MenuIndex);
		}

		public void MailingCallback(IAsyncResult ar)
		{
			// Restore orginial state
			ASyncMailingState mailingState = (ASyncMailingState)ar.AsyncState;
			
			//retrieve the object on which End needs to be called
			ASyncMailing mailing = mailingState.AsyncMailing;
			mailing.EndMailIt(ar);

			// Let the world know that mailing is finished
			SyncDataStore.SetRecords(mailingState.SessionId, true);
		}

	}
}
